<template>
  <div class="body">
    <div class="tit">修改个人信息</div>
    <div class="tot">
      <div class="tx">
        <img class="avatar" :src="avatarUrl" alt="User Avatar" @click="openFilePicker" />
        <input type="file" id="avatarInput" ref="fileInput" accept="image/*" style="display: none"
          @change="handleFileChange" />
      </div>
      <div class="ema">
        <div class="ew">*用户邮箱</div>
        <el-input placeholder="请输入内容" v-model="email" :disabled="true"></el-input>
      </div>
      <div class="ema" v-if="password != ''">
        <div class="ew">*原密码</div>
        <el-input placeholder="请输入您原来的密码" v-model="initPassword" show-password></el-input>
      </div>
      <div class="ema">
        <div class="ew">*现密码</div>
        <el-input placeholder="请输入您要修改的密码" v-model="currentPassword" show-password></el-input>
      </div>
      <div class="ema">
        <div class="ew">*再次输入</div>
        <el-input placeholder="请再次输入您要修改的密码" v-model="currentPassword1" show-password></el-input>
      </div>
      <div class="ema">
        <div class="ew">*用户名</div>
        <el-input placeholder="请输入您的用户名" v-model="userName" class="dua"></el-input>
      </div>
      <div class="ema">
        <div class="ew">*年龄</div>
        <el-input placeholder="请输入您的年龄" v-model="age" class="dua"></el-input>
      </div>
      <div class="ema">
        <div class="ew">*性别</div>
        <el-radio-group v-model="sex">
          <el-radio label="男"></el-radio>
          <el-radio label="女"></el-radio>
        </el-radio-group>
      </div>
      <div class="ema1">
        <div class="ew1">*个性签名</div>
        <el-input type="textarea" placeholder="请输入内容" v-model="signature" maxlength="50" show-word-limit>
        </el-input>
      </div>
      <div class="tip">
        <i class="el-icon-s-opportunity"></i>tips:&nbsp;若没有设置过密码则跳过原密码直接设置现密码就行，否则请校验自己原密码的正确性。(现密码可以和原密码相同)
      </div>
    </div>
    <div class="su" @click="submit1">提交更改</div>
  </div>
</template>
<script>
import axios from "axios";
export default {
  data() {
    return {
      userId: this.$route.params.userId,
      userName: "",
      txUrl: "",
      avatarUrl: "",
      email: "",
      password: "",
      initPassword: "",
      currentPassword: "",
      currentPassword1: "",
      age: "",
      sex: "",
      signature: "",
    };
  },
  methods: {
    hqy() {
      let _this = this;
      const axios = require("axios");
      let data = JSON.stringify({
        "userID": _this.userId,
      });
      let config = {
        method: "post",
        maxBodyLength: Infinity,
        url: "http://8.134.215.31:11112/userMessage/get",
        headers: {
          "Content-Type": "application/json",
          "token": localStorage.getItem("JWT_TOKEN"),
        },
        data: data,
      };
      axios
        .request(config)
        .then((response) => {
          _this.userName = response.data.data.username;
          _this.txUrl = response.data.data.txUrl;
          _this.avatarUrl = response.data.data.txUrl;
          _this.sex = response.data.data.sex;
          _this.age = response.data.data.age;
          _this.signature = response.data.data.signature;
          _this.email = response.data.data.email;
          _this.password = response.data.data.password;
          _this.currentPassword = response.data.data.password;
          _this.currentPassword1 = response.data.data.password;
          const param1 = _this.userId;
          const param2 = _this.txUrl;
          const param3 = _this.$route.name;
          const param4 = _this.userName;
          _this.$emit("childEvent", { param1, param2, param3, param4 });
        })
        .catch((error) => {
          console.log(error);
        });
    },
    openFilePicker(event) {
      event.stopPropagation(); // 阻止事件冒泡
      this.$refs.fileInput.click();
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        this.displaySelectedImage(file);
      }
    },
    displaySelectedImage(file) {
      const reader = new FileReader();
      reader.onload = (event) => {
        this.avatarUrl = event.target.result;
        console.log(this.avatarUrl);
        this.$forceUpdate();
        this.uploadAvatarToBackend();
      };
      reader.readAsDataURL(file);
    },
    async uploadAvatarToBackend() {
      let _this = this;
      const file = this.$refs.fileInput.files[0];
      const formData = new FormData();
      formData.append("avatar", file);
      formData.append("userID", _this.userId);
      console.log(formData);
      const response = await axios.request({
        method: "post",
        maxBodyLength: Infinity,
        url: "http://8.134.215.31:11112/uploadAvatar",
        headers: {
          "Content-Type": "multipart/form-data"
        },
        data: formData,
      }).then((response) => {
        if (response.data.code == 1) {
          _this.txUrl = response.data.avatarUrl;
        } else {
          alert(response.data.message);
        }
      }).catch((error) => {
        console.error("Error uploading avatar:", error);
      })
    },

    submit() {
      let _this = this;
      const axios = require("axios");
      let data = JSON.stringify({
        "userID": _this.userId,
        "password": _this.currentPassword,
        "txUrl": _this.txUrl,
        "username": _this.userName,
        "age": _this.age,
        "sex": _this.sex,
        "signature": _this.signature,
      });
      let config = {
        method: "post",
        maxBodyLength: Infinity,
        url: "http://8.134.215.31:11112/correctMessage/post",
        headers: {
          "Content-Type": "application/json",
        },
        data: data,
      };
      axios
        .request(config)
        .then((response) => {
          _this.$message({
            message: response.data.msg,
            type: "success",
          });
          _this.$router.push(`/home/homePage/${_this.userId}`);
          console.log(response);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    submit1() {
      if (this.currentPassword == "" || this.currentPassword1 == "")
        this.$message({
          showClose: true,
          message: "请完善表格信息",
        });
      else if (this.password != "" && this.initPassword == "")
        this.$message({
          showClose: true,
          message: "请完善表格信息",
        });
      else if (this.initPassword != this.password)
        this.$message({
          showClose: true,
          message: "原密码错误",
        });
      else {
        this.submit();
      }
    }
  },
  mounted() {
    this.hqy();
  },
};
</script>
<style scoped>
.body {
  overflow: hidden;
  user-select: none;
  height: auto;
  min-height: 1000px;
  width: 100%;
}

.tit {
  width: 20%;
  height: 50px;
  margin: 20px auto;
  line-height: 50px;
  text-align: center;
  font-size: 24px;
  font-weight: 600;
}

.tot {
  /* overflow: hidden; */
  width: 60%;
  min-height: 600px;
  height: auto;
  margin: 0 auto;
  background-color: pink;
  border-radius: 10px;
  padding: 10px;
}

.tx {
  width: 100%;
  height: auto;
  background-color: pink;
  margin-bottom: 20px;
}

.ema {
  position: relative;
  width: 100%;
  height: 40px;
  margin-bottom: 20px;
}

.ew {
  position: absolute;
  left: 5%;
  top: 0%;
  width: 10%;
  height: 100%;
  line-height: 40px;
  text-align: center;
  font-weight: 550;
}

.ema .el-input {
  position: absolute;
  left: 20%;
  top: 0%;
  width: 50%;
  height: 100%;
}

.ema .dua {
  width: 20%;
}

.el-radio-group {
  position: absolute;
  left: 20%;
  top: 0%;
  width: 50%;
  height: 100%;
}

::v-deep .el-radio {
  margin: 13px 0;
  margin-right: 30px;
}

.ema1 {
  position: relative;
  width: 100%;
  height: 110px;
  margin-bottom: 20px;
}

.ew1 {
  position: absolute;
  width: 10%;
  height: 40px;
  top: 0%;
  left: 5%;
  line-height: 40px;
  font-weight: 550;
  text-align: center;
}

.el-textarea {
  position: absolute;
  left: 20%;
  top: 0%;
  width: 50%;
  height: 100px;
}

::v-deep .el-textarea__inner {
  height: 100%;
}

.tip {
  width: 100%;
  height: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  text-indent: 2em;
  color: blue;
}

.su {
  width: 10%;
  height: 50px;
  background-color: rgba(74, 82, 89);
  border-radius: 10px;
  margin: 20px auto;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  font-weight: 500;
  color: white;
}

.su:hover {
  cursor: pointer;
  background-color: rgba(74, 82, 89, 0.8);
}

.su:active {
  background-color: rgba(74, 82, 89);
}

.avatar {
  padding: 10px 15px;
  margin: 10px 25px;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  /* 将头像显示为圆形 */
  cursor: pointer;
}
</style>